package com.lxn.hrm.service.impl;

import com.alibaba.fastjson.JSON;
import com.lxn.dto.SMSSendDTO;
import com.lxn.hrm.feignclients.RedisFeignClient;
import com.lxn.hrm.service.IVerifyCodeService;
import com.lxn.hrm.util.AjaxResult;
import com.lxn.hrm.util.HttpUtil;
import com.lxn.hrm.util.StrUtils;
import com.lxn.hrm.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class VerifyCodeServiceImpl implements IVerifyCodeService {
    @Autowired
    private RedisFeignClient redisFeignClient ;

    @Override
    public String createImageCode(String imageCodeKey) throws IOException {
        if(!StringUtils.hasLength(imageCodeKey)){
            throw new RuntimeException("无效的imageCodeKey");
        }
        //UUID生成验证码
        String imageCodeValue = UUID.randomUUID().toString().substring(0,4);

        //根据imageCodeKey为key把验证码存到Redis并设置过期时间
        redisFeignClient.setex(imageCodeKey,300,imageCodeValue);

        return VerifyCodeUtils.verifyCode(135,40,imageCodeValue);
    }

    @Override
    public void sendSmsCode(Map<String, String> map) {
        String imageCode = map.get("imageCode");
        String imageCodeKey = map.get("imageCodeKey");
        String phone = map.get("mobile");
        if(!StringUtils.hasLength(imageCode) || !StringUtils.hasLength(imageCodeKey) || !StringUtils.hasLength(phone)  ){
            throw new RuntimeException("无效参数");
        }
        //检验图片验证码,根据key从Redis中获取图片验证码
        AjaxResult ajaxResult = redisFeignClient.get(imageCodeKey);
        if(!ajaxResult.isSuccess() || ajaxResult.getResultObj() == null){
            throw new RuntimeException("无效图片验证码，请重新发送!");
        }
        //redis中的图片验证码和验证码比较
        String imageCodeValue = ajaxResult.getResultObj().toString();
        if(!imageCodeValue.equals(imageCode)){
            throw new RuntimeException("错误的图片验证码，请重新发送");
        }
        String smsCodeRedisKey = "sms:"+phone;
        Date nowDate = new Date();
        //获取上一次验证码
        AjaxResult lastAjaxResult = redisFeignClient.get(smsCodeRedisKey);
        String smsCode = null;

        if(lastAjaxResult.isSuccess() && lastAjaxResult.getResultObj() != null){
            //验证码发送时间间隔是否大于60秒
            SMSSendDTO lastSmsSendDTO = JSON.parseObject(lastAjaxResult.getResultObj().toString(), SMSSendDTO.class);
            if((nowDate.getTime() - lastSmsSendDTO.getSendTime()) < 60000){
                throw new RuntimeException("发送频繁，请稍后重新发送!");
            }
            //使用上一次验证码
            smsCode = lastSmsSendDTO.getCode();
        }else{
            //上一次没有，则创建新的验证码
            smsCode = StrUtils.getRandomString(6);
        }
        //验证码发送记录保存到Redis
        String senDTOJson = JSON.toJSONString(new SMSSendDTO(smsCode, phone, nowDate.getTime()));
        redisFeignClient.setex(smsCodeRedisKey,300,senDTOJson);

        //发送短信
        String sendMessage = "验证码为["+smsCode+"]，请在5分钟内使用";
        System.out.println(sendMessage);

        Map<String,String> smsMap = new HashMap<>();
        smsMap.put("Uid","hwerth");
        smsMap.put("Key","d41d8cd98f00b204e980");
        smsMap.put("smsMob",phone);
        smsMap.put("smsText",sendMessage);

        String result = HttpUtil.sendPost("http://utf8.api.smschinese.cn/",smsMap);
        if(Integer.valueOf(result) == -1){
            throw new RuntimeException("短信发送失败：【-1 没有账户】，请联系管理员");
        }
        if(Integer.valueOf(result) < 0){
            throw new RuntimeException("短信发送失败");
        }
    }
}
